package com.kexio.scheduler.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import com.kexio.common.dto.Result;
import com.kexio.scheduler.entity.ScheduledJob;
import com.kexio.scheduler.service.SchedulerService;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 调度服务实现 (简化版)
 * 
 * @author Kexio Team
 * @since 1.0.0
 */
@Service
@ConditionalOnProperty(prefix = "kexio.scheduler", name = "enabled", havingValue = "true")
public class SchedulerServiceImpl implements SchedulerService {
    
    private static final Logger logger = LoggerFactory.getLogger(SchedulerServiceImpl.class);
    
    // 模拟存储 (实际应该注入Mapper)
    private final Map<String, ScheduledJob> jobStorage = new ConcurrentHashMap<>();
    
    // 调度器状态
    private volatile boolean schedulerRunning = false;
    
    @Override
    public Result<Boolean> addJob(ScheduledJob job) {
        try {
            if (job == null || StrUtil.isBlank(job.getJobName())) {
                return Result.error("任务信息不完整");
            }
            
            // 生成ID
            if (StrUtil.isBlank(job.getId())) {
                job.setId(IdUtil.fastSimpleUUID());
            }
            
            // 设置默认值
            if (StrUtil.isBlank(job.getStatus())) {
                job.setStatus("WAITING");
            }
            
            // 保存任务
            jobStorage.put(job.getId(), job);
            
            logger.info("定时任务添加成功: jobId={}, jobName={}, cron={}", 
                       job.getId(), job.getJobName(), job.getCronExpression());
            
            return Result.success("任务添加成功", true);
            
        } catch (Exception e) {
            logger.error("添加定时任务异常", e);
            return Result.error("添加定时任务异常: " + e.getMessage());
        }
    }
    
    @Override
    public Result<Boolean> updateJob(ScheduledJob job) {
        try {
            if (job == null || StrUtil.isBlank(job.getId())) {
                return Result.error("任务ID不能为空");
            }
            
            ScheduledJob existingJob = jobStorage.get(job.getId());
            if (existingJob == null) {
                return Result.error("任务不存在");
            }
            
            // 更新任务信息
            jobStorage.put(job.getId(), job);
            
            logger.info("定时任务更新成功: jobId={}, jobName={}", job.getId(), job.getJobName());
            
            return Result.success("任务更新成功", true);
            
        } catch (Exception e) {
            logger.error("更新定时任务异常", e);
            return Result.error("更新定时任务异常: " + e.getMessage());
        }
    }
    
    @Override
    public Result<Boolean> deleteJob(String jobId) {
        try {
            if (StrUtil.isBlank(jobId)) {
                return Result.error("任务ID不能为空");
            }
            
            ScheduledJob job = jobStorage.remove(jobId);
            if (job == null) {
                return Result.error("任务不存在");
            }
            
            logger.info("定时任务删除成功: jobId={}, jobName={}", jobId, job.getJobName());
            
            return Result.success("任务删除成功", true);
            
        } catch (Exception e) {
            logger.error("删除定时任务异常: jobId={}", jobId, e);
            return Result.error("删除定时任务异常: " + e.getMessage());
        }
    }
    
    @Override
    public Result<Boolean> startJob(String jobId) {
        try {
            ScheduledJob job = jobStorage.get(jobId);
            if (job == null) {
                return Result.error("任务不存在");
            }
            
            job.setStatus("WAITING");
            
            logger.info("定时任务启动成功: jobId={}, jobName={}", jobId, job.getJobName());
            
            return Result.success("任务启动成功", true);
            
        } catch (Exception e) {
            logger.error("启动定时任务异常: jobId={}", jobId, e);
            return Result.error("启动定时任务异常: " + e.getMessage());
        }
    }
    
    @Override
    public Result<Boolean> pauseJob(String jobId) {
        try {
            ScheduledJob job = jobStorage.get(jobId);
            if (job == null) {
                return Result.error("任务不存在");
            }
            
            job.setStatus("PAUSED");
            
            logger.info("定时任务暂停成功: jobId={}, jobName={}", jobId, job.getJobName());
            
            return Result.success("任务暂停成功", true);
            
        } catch (Exception e) {
            logger.error("暂停定时任务异常: jobId={}", jobId, e);
            return Result.error("暂停定时任务异常: " + e.getMessage());
        }
    }
    
    @Override
    public Result<Boolean> resumeJob(String jobId) {
        try {
            ScheduledJob job = jobStorage.get(jobId);
            if (job == null) {
                return Result.error("任务不存在");
            }
            
            job.setStatus("WAITING");
            
            logger.info("定时任务恢复成功: jobId={}, jobName={}", jobId, job.getJobName());
            
            return Result.success("任务恢复成功", true);
            
        } catch (Exception e) {
            logger.error("恢复定时任务异常: jobId={}", jobId, e);
            return Result.error("恢复定时任务异常: " + e.getMessage());
        }
    }
    
    @Override
    public Result<Boolean> executeJob(String jobId) {
        try {
            ScheduledJob job = jobStorage.get(jobId);
            if (job == null) {
                return Result.error("任务不存在");
            }
            
            // 模拟执行任务
            job.setStatus("RUNNING");
            job.setLastExecuteTime(LocalDateTime.now());
            job.setExecuteCount(job.getExecuteCount() + 1);
            
            // 模拟执行结果
            boolean success = Math.random() > 0.2; // 80%成功率
            
            if (success) {
                job.setStatus("SUCCESS");
                job.setSuccessCount(job.getSuccessCount() + 1);
                logger.info("定时任务执行成功: jobId={}, jobName={}", jobId, job.getJobName());
            } else {
                job.setStatus("FAILED");
                job.setFailCount(job.getFailCount() + 1);
                logger.warn("定时任务执行失败: jobId={}, jobName={}", jobId, job.getJobName());
            }
            
            if (success) {
                return Result.success("任务执行成功", true);
            } else {
                return Result.error("任务执行失败");
            }
            
        } catch (Exception e) {
            logger.error("执行定时任务异常: jobId={}", jobId, e);
            return Result.error("执行定时任务异常: " + e.getMessage());
        }
    }
    
    @Override
    public ScheduledJob getJob(String jobId) {
        return jobStorage.get(jobId);
    }
    
    @Override
    public List<ScheduledJob> getAllJobs() {
        return new ArrayList<>(jobStorage.values());
    }
    
    @Override
    public List<ScheduledJob> getJobsByStatus(String status) {
        List<ScheduledJob> result = new ArrayList<>();
        for (ScheduledJob job : jobStorage.values()) {
            if (status.equals(job.getStatus())) {
                result.add(job);
            }
        }
        return result;
    }
    
    @Override
    public List<ScheduledJob> getJobsByGroup(String jobGroup) {
        List<ScheduledJob> result = new ArrayList<>();
        for (ScheduledJob job : jobStorage.values()) {
            if (jobGroup.equals(job.getJobGroup())) {
                result.add(job);
            }
        }
        return result;
    }
    
    @Override
    public Map<String, Object> getSchedulerStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("running", schedulerRunning);
        status.put("totalJobs", jobStorage.size());
        status.put("runningJobs", getJobsByStatus("RUNNING").size());
        status.put("waitingJobs", getJobsByStatus("WAITING").size());
        status.put("pausedJobs", getJobsByStatus("PAUSED").size());
        status.put("startTime", LocalDateTime.now());
        return status;
    }
    
    @Override
    public Result<Boolean> startScheduler() {
        schedulerRunning = true;
        logger.info("定时任务调度器启动成功");
        return Result.success("调度器启动成功", true);
    }
    
    @Override
    public Result<Boolean> stopScheduler() {
        schedulerRunning = false;
        logger.info("定时任务调度器停止成功");
        return Result.success("调度器停止成功", true);
    }
    
    @Override
    public Result<Boolean> pauseScheduler() {
        schedulerRunning = false;
        logger.info("定时任务调度器暂停成功");
        return Result.success("调度器暂停成功", true);
    }
    
    @Override
    public Result<Boolean> resumeScheduler() {
        schedulerRunning = true;
        logger.info("定时任务调度器恢复成功");
        return Result.success("调度器恢复成功", true);
    }
    
    @Override
    public Map<String, Object> getJobStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        int totalJobs = jobStorage.size();
        int totalExecutions = 0;
        int totalSuccesses = 0;
        int totalFailures = 0;
        
        for (ScheduledJob job : jobStorage.values()) {
            totalExecutions += job.getExecuteCount();
            totalSuccesses += job.getSuccessCount();
            totalFailures += job.getFailCount();
        }
        
        stats.put("totalJobs", totalJobs);
        stats.put("totalExecutions", totalExecutions);
        stats.put("totalSuccesses", totalSuccesses);
        stats.put("totalFailures", totalFailures);
        stats.put("successRate", totalExecutions > 0 ? 
                  String.format("%.2f%%", (double) totalSuccesses / totalExecutions * 100) : "0%");
        
        return stats;
    }
    
    @Override
    public int cleanExpiredExecutions(int days) {
        // 模拟清理过期执行记录
        logger.info("清理{}天前的执行记录", days);
        return 0;
    }
}
